package cn.hhchat.wp.security.controller;

import cn.hhchat.wp.config.SystemProperties;
import cn.hhchat.wp.dto.msg.RMsg;
import cn.hhchat.wp.dto.msg.RMsgFactory;
import cn.hhchat.wp.dto.msg.RMsgModel;
import cn.hhchat.wp.dto.user.SimpleUser;
import cn.hhchat.wp.entity.UserEntity;
import cn.hhchat.wp.security.service.*;
import cn.hhchat.wp.service.UserService;
import cn.hhchat.wp.util.SessionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
public class AuthenticationRestController {

    private String tokenHeader;

    private final AuthenticationManager authenticationManager;
    private final JwtTokenUtil jwtTokenUtil;
    private final JwtUserDetailsServiceImpl userDetailsService;

    @Autowired
    public AuthenticationRestController(AuthenticationManager authenticationManager, JwtTokenUtil jwtTokenUtil, JwtUserDetailsServiceImpl userDetailsService, UserService userService, SystemProperties sysConfig) {
        this.authenticationManager = authenticationManager;
        this.jwtTokenUtil = jwtTokenUtil;
        this.userDetailsService = userDetailsService;
        this.userService = userService;
        this.tokenHeader = sysConfig.getJwt().getHeader();
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public RMsg createAuthenticationToken(@RequestBody JwtAuthenticationRequest authenticationRequest) throws AuthenticationException {

        log.info(" ⛅ "+authenticationRequest.getUsername()+" try to login");
        // Perform the security
        final Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(
                        authenticationRequest.getUsername(),
                        authenticationRequest.getPassword()
                )
        );
        SecurityContextHolder.getContext().setAuthentication(authentication);
        final UserDetails userDetails = userDetailsService.loadUserByUsername(authenticationRequest.getUsername());

        // Reload password post-security so we can generate token
        final String token = jwtTokenUtil.generateToken(userDetails,"web");

        //保存到session
        UserEntity userEntity = userService.getByUsername(authenticationRequest.getUsername());
        SessionUtil.saveUserToSession(userEntity);

        // Return the token
        SimpleUser user = userEntity.toSimpleUser();
        return RMsgFactory.ok(new RMsgModel().add("token",token).add("user",user).data());
    }


    @RequestMapping(value = "refresh", method = RequestMethod.GET)
    public ResponseEntity<?> refreshAndGetAuthenticationToken(HttpServletRequest request) {
        String token = request.getHeader(tokenHeader);
        String username = jwtTokenUtil.getUsernameFromToken(token);
        JwtUser user = (JwtUser) userDetailsService.loadUserByUsername(username);

        if (jwtTokenUtil.canTokenBeRefreshed(token, user.getLastPasswordResetDate())) {
            String refreshedToken = jwtTokenUtil.refreshToken(token);
            return ResponseEntity.ok(new JwtAuthenticationResponse(refreshedToken));
        } else {
            return ResponseEntity.badRequest().body(null);
        }
    }

    @GetMapping("getAll")
    public RMsg getAll() {
        List<SimpleUser> users = userService.getAll().stream().map(UserEntity::toSimpleUser).collect(Collectors.toList());
        return RMsgFactory.ok(users);
    }


    private final UserService userService;

}
